﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Common;
using StoragePeriod.Data;

namespace StoragePeriod.Web.SysManage
{
    public partial class SysRolePrivilegeManage : SecurityPage
    {
        private string BackValue { get { return Request["backvalue"]; } }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTree();
                LoadPageStatus();
            }
        }

        private void LoadPageStatus()
        {
            if (!BackValue.IsNullOrEmpty())
            {
                tvRoleView.Nodes.AllNodes().FirstOrDefault(p => p.Value == BackValue).Select();
                lbSelected.Text = tvRoleView.SelectedNode.Text;
                hdRoleCode.Value = tvRoleView.SelectedValue;
                LoadRoleUserAndprivilege(tvRoleView.SelectedNode.Value);
            }
        }

        private void BindTree()
        {
            TreeNode rootNode = new TreeNode()
            {
                Text = "全部角色"
            };
            Role.All().ToList().ForEach(p =>
            {
                rootNode.ChildNodes.Add(new TreeNode()
                {
                    Text = p.RoleName,
                    Value = p.RoleCode
                });
            });

            tvRoleView.Nodes.Add(rootNode);
        }

        protected void tvRoleView_SelectedNodeChanged(object sender, EventArgs e)
        {
            LoadRoleUserAndprivilege(tvRoleView.SelectedNode.Value);
            hdRoleCode.Value = tvRoleView.SelectedNode.Value;
            lbSelected.Text = tvRoleView.SelectedNode.Text;
        }

        private void LoadRoleUserAndprivilege(string p)
        {
            gvRoleprivilegeView.DataSource = RolePrivileges.Where("RoleCode==@0", p).Select(a => new { 权限名=a.PrivCode,角色名=a.RoleCode,权限编码 =a.PrivCode}); 
            gvRoleprivilegeView.DataBind();

        }

        protected void gvprivilegeView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            RolePrivileges.Delete("PrivCode==@0 and RoleCode=@1", e.Keys[0].EToString(), e.Keys[1].EToString());

            Page.Alert(string.Format("权限：{0} 删除成功", e.Values[1].EToString()));
        }

        protected void gvRoleUserView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            RoleUsers.Delete("UserCode==@0 and RoleCode=@1", e.Keys[0].EToString(), e.Keys[1].EToString());

            Page.Alert(string.Format("用户：{0} 删除成功", e.Keys[0].EToString()));
        }

        protected void gvRoleprivilegeView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            (sender as GridView).PageIndex = e.NewPageIndex;
            LoadRoleUserAndprivilege(tvRoleView.SelectedNode.Value);
        }
 
    }
}